/*Copyright (C) 2010-2012 RAAFCOM B.V. All rights reserved.

This file is part of Velsto and may be used under the terms of:
The GNU General Public License version 3 or higher, as published by
the Free Software Foundation.

This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.*/
/* 
* Application  : Velsto
* Class        : FormMap
* Class to produce Map using MapWindow ActiveX controls (www.mapwindow.org).
* Basis Mapwindow wiki Legend example.
* Commented out use of resources(caused crash).
* Added xyz indicator,contours,selection for lighting and colorscheme
* Commented out not usefull toolbar buttons
* Called from FormMain
* 28/08/2010-  : M.A.van Ravesteijn (Raafcom)
*   13/01/2012   Initial version v1.0
* 07/05/2012   : M.A.van Ravesteijn (Raafcom)
*                v1.1 added save as xyz function
* 06->08 2012  : v1.2 complete revision
 *               -- added GridColorAnalyser
 *               -- added Residuals Workflow
 *               -- Colorschemes now separate class.
 *               -- various code revisions
* 
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Globalization;
//using TableEditorNew.BO;
//using TableEditorNew.Forms;
using mwSymbology.Forms;

namespace Velsto
{
    public delegate void ContourDelegate(int cntInt, double cntMin, double cntMax);

	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class FormMap : System.Windows.Forms.Form, MapWinGIS.ICallback
	{
		//member variables
        private SelectDelegate sd;
		private int m_GroupHandle;

        private SimulationEntity se;
		private LegendControl.Legend legend1;
		private AxMapWinGIS.AxMap axMap1;
        private MapWinGIS.Grid grid;
        private MapWinGIS.Image image;
        private MapWinGIS.Shapefile shpfile_cont;
        private MapWinGIS.Shapefile shpfile_depth;
        private GraphicHistogram graphicHistogram;
        private ArrayList arx1;
        private ArrayList ary1;
        private float xLeft,xRight;
        private float rightReal, leftReal;
        private bool mouseOverLeft,mouseOverRight;
        private bool mouseDownLeft,mouseDownRight;
        private bool graphCreated = false;
        float minD, maxD, maxS;
        private MapWinGIS.Shapefile shpfile_open;
        private MapWinGIS.Shapefile shpfile_open2;
        private string shpfilename_open;
        private string filename_open;
        private bool shpfile_opened = false;
        private MapWinGIS.Shapefile shpfile_mar;
        private string shpfilename_mar="";
        private string filename_mar="";
        private MapWinGIS.Shapefile shpfile_res;
        private string shpfilename_res="";
        private string filename_res="";
        private int handle_depth = -1;
        private int handle_contour = -1;
        private int handle_grid;
        private int rwf_phase = Constants.RWF_PHASE_MARKERS;
        private bool resWorkflow;
        private double meanz = 0.0, stdevz = 0.0;
        TableEditorNew.Forms.frmTableEditor te1;
        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1;
        private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem labelsToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem labelerToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem helperToolStripMenuItem;
        private System.Windows.Forms.ToolBar toolBar1;
		private System.Windows.Forms.ImageList imageList1;
		private System.Windows.Forms.ToolBarButton tbAdd;
		private System.Windows.Forms.ToolBarButton tbRemove;
		private System.Windows.Forms.ToolBarButton tbClear;
		private System.Windows.Forms.StatusBar statusBar1;
		private System.Windows.Forms.StatusBarPanel pMessage;
		private System.Windows.Forms.StatusBarPanel pProgressBar;
		private System.Windows.Forms.ProgressBar progressBar1;
		private System.Windows.Forms.ToolBarButton tbZoomIn;
		private System.Windows.Forms.ToolBarButton tbZoomOut;
		private System.Windows.Forms.ToolBarButton tbFullExtents;
		private System.Windows.Forms.ToolBarButton tbPan;
		private System.Windows.Forms.Panel panel1;
		private System.Windows.Forms.ContextMenu contextMenu1;
		private System.Windows.Forms.MenuItem menuItem3;
		private System.Windows.Forms.MenuItem menuAddGroup;
		private System.Windows.Forms.MenuItem menuRemoveGroup;
		private System.Windows.Forms.MenuItem menuExpandGroup;
		private System.Windows.Forms.MenuItem menuExpandAll;
		private System.Windows.Forms.MenuItem menuCollapseAll;
		private System.Windows.Forms.MenuItem menuCollapseGroup;
		private System.Windows.Forms.MenuItem menuRenameGroup;
		private System.Windows.Forms.MenuItem menuRenameLayer;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.ToolBar toolBar2;
		private System.Windows.Forms.Panel panel2;
		private System.Windows.Forms.Splitter splitter1;
		private System.Windows.Forms.ToolBarButton tbMoveGroupDown;
		private System.Windows.Forms.ToolBarButton tbMoveGroupUp;
		private System.Windows.Forms.ToolBarButton tbSetGroupIcon;
		private System.Windows.Forms.ToolBarButton tbSetLayerIcon;
		private System.ComponentModel.IContainer components;
        private System.Windows.Forms.TrackBar trb1;
        private System.Windows.Forms.TrackBar trb2;
        private System.Windows.Forms.TrackBar trb3;
        private System.Windows.Forms.Label lb1;
        private System.Windows.Forms.Label lb2;
        private System.Windows.Forms.Label lb3;
        private System.Windows.Forms.Label lb4;
        private System.Windows.Forms.Label lbgrid;
        private System.Windows.Forms.Panel panel3;
        private System.Windows.Forms.ComboBox cb1;
        private System.Windows.Forms.Button bu1;
        private System.Windows.Forms.Button bu2;
        private System.Windows.Forms.Button bu3;
        private System.Windows.Forms.Button bu4;
        private System.Windows.Forms.Button buedit_mar;
        private System.Windows.Forms.Button buedit_res;
        private System.Windows.Forms.PictureBox pb1;
        private System.Windows.Forms.RadioButton rbmar;
        private System.Windows.Forms.RadioButton rbres;
        private System.Windows.Forms.RadioButton rbvar;
        private System.Windows.Forms.Label lbres_mean;
        private System.Windows.Forms.Label lbres_stdev;
        private System.Windows.Forms.Label lbres;
        private string formText;
        private bool bgridcalc;
        private ToolTip tt2;
        
        public FormMap()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//**Initialize the legend control**//
		    legend1.Map =(MapWinGIS.Map)axMap1.GetOcx();
		}

        public FormMap(bool bgridcalc2, bool rwf, SelectDelegate sd1, SimulationEntity se2, string formText2)
        {
            //
            // Required for Windows Form Designer support
            //
            //MessageBox.Show(rwf.ToString());
            bgridcalc = bgridcalc2;
            resWorkflow = rwf;
            sd = sd1;
            se = new SimulationEntity(se2);
            formText = formText2;
            InitializeComponent();
            this.Text = formText;
            
            //**Initialize the legend control**//
            legend1.Map = (MapWinGIS.Map)axMap1.GetOcx();
            // add Grid
            AddLayer(se.MapFile, false, true);
            // add shapefiles
            if (se.MapType == Constants.MAP_Z_WELL)
            {
                AddLayer(se.Shpfilename_mar, false, true);
            } 
            else if (se.MapType == Constants.MAP_RES_KRIG)
            {
                AddLayer(se.Shpfilename_open, false, true);
            }
            else if (se.MapType == Constants.MAP_ZDEV_WELL2)
            {
                AddLayer(se.Shpfilename_open, false, true);
            }
            else if (resWorkflow && se.WellTvdMarkerFile != "")
            {
                // open depth file and convert to shapefile and add
                se.TempFolderpath = Path.GetTempPath();
                rwf_phase = Constants.RWF_PHASE_MARKERS;
                se.Rwf_phase = rwf_phase;
                shpfile_open = new MapWinGIS.ShapefileClass();
                XYPointFile xyf1 = new XYPointFile();
                shpfile_open = xyf1.file2Shape(se.WellTvdMarkerFile, ref se);
                if (se.ErrorMessage != null)
                {
                    MessageBox.Show(this, se.ErrorMessage, "**Error**",
                    MessageBoxButtons.OK);
                    return;
                }
                filename_open = se.WellTvdMarkerFile;
                this.Text = formText + " depthfile=" + filename_open;
                shpfilename_open = se.TempFolderpath + Guid.NewGuid().ToString() + ".shp";
                se.Shpfilename_open = shpfilename_open;
                shpfile_open.SaveAs(shpfilename_open, null);
                AddLayer(shpfilename_open, false, false);
                shpfile_opened = true;
                saveToolStripMenuItem.Enabled = true;
                saveAsToolStripMenuItem.Enabled = true;

            }
            rwf_phase = Constants.RWF_PHASE_MARKERS;
            se.Rwf_phase = rwf_phase;
        }
        private void FormMap_Load(object sender, EventArgs e)
        {
            ToolTip tt1 = new ToolTip();
            tt1.SetToolTip(bu3,"Histogram of grid values with windowed colorscheme. Depth window maybe changed by moving vertical lines.\nColorscheme is between depths of vertical lines, to the left and right are the min and max colors");
            tt1.AutomaticDelay = 2000;
            tt2 = new ToolTip();
            tt2.AutoPopDelay = 0;
            tt2.InitialDelay = 10;
            tt2.AutomaticDelay = 2000;
            tt2.UseAnimation = true;
            ToolTip tt3 = new ToolTip();
            tt3.SetToolTip(buedit_mar,"Edit depths (99999 is nodata value)");
            tt3.InitialDelay = 1;
            tt3.AutomaticDelay = 2000;
            ToolTip tt4 = new ToolTip();
            tt4.SetToolTip(buedit_res, "Edit depths (99999 is nodata value)");
            tt4.InitialDelay = 1;
            tt4.AutomaticDelay = 2000;
        }
        
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
        /// 

		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(FormMap));
			this.legend1 = new LegendControl.Legend();
			this.axMap1 = new AxMapWinGIS.AxMap();
			this.toolBar1 = new System.Windows.Forms.ToolBar();
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
            this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.saveToolStripMenuItem.Enabled = false;
            this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.saveAsToolStripMenuItem.Enabled = false;
            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.labelsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.labelerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.helperToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.tbAdd = new System.Windows.Forms.ToolBarButton();
			this.tbRemove = new System.Windows.Forms.ToolBarButton();
			this.tbClear = new System.Windows.Forms.ToolBarButton();
			this.tbZoomIn = new System.Windows.Forms.ToolBarButton();
			this.tbZoomOut = new System.Windows.Forms.ToolBarButton();
			this.tbFullExtents = new System.Windows.Forms.ToolBarButton();
			this.tbPan = new System.Windows.Forms.ToolBarButton();
			this.imageList1 = new System.Windows.Forms.ImageList(this.components);
			this.statusBar1 = new System.Windows.Forms.StatusBar();
			this.pMessage = new System.Windows.Forms.StatusBarPanel();
			this.pProgressBar = new System.Windows.Forms.StatusBarPanel();
			this.progressBar1 = new System.Windows.Forms.ProgressBar();
			this.panel1 = new System.Windows.Forms.Panel();
			this.contextMenu1 = new System.Windows.Forms.ContextMenu();
			this.menuAddGroup = new System.Windows.Forms.MenuItem();
			this.menuRemoveGroup = new System.Windows.Forms.MenuItem();
			this.menuItem3 = new System.Windows.Forms.MenuItem();
			this.menuExpandGroup = new System.Windows.Forms.MenuItem();
			this.menuExpandAll = new System.Windows.Forms.MenuItem();
			this.menuCollapseGroup = new System.Windows.Forms.MenuItem();
			this.menuCollapseAll = new System.Windows.Forms.MenuItem();
			this.menuRenameGroup = new System.Windows.Forms.MenuItem();
			this.menuRenameLayer = new System.Windows.Forms.MenuItem();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.toolBar2 = new System.Windows.Forms.ToolBar();
			this.tbMoveGroupDown = new System.Windows.Forms.ToolBarButton();
			this.tbMoveGroupUp = new System.Windows.Forms.ToolBarButton();
			this.panel2 = new System.Windows.Forms.Panel();
            this.panel3 = new System.Windows.Forms.Panel();
            this.splitter1 = new System.Windows.Forms.Splitter();
			this.tbSetGroupIcon = new System.Windows.Forms.ToolBarButton();
			this.tbSetLayerIcon = new System.Windows.Forms.ToolBarButton();
            this.lb1 = new Label();
            this.lb2 = new Label();
            this.lb3 = new Label();
            this.lb4 = new Label();
            this.lbgrid = new Label();
            this.trb1 = new System.Windows.Forms.TrackBar();
            this.trb2 = new System.Windows.Forms.TrackBar();
            this.trb3 = new System.Windows.Forms.TrackBar();
            this.cb1 = new System.Windows.Forms.ComboBox();
            this.bu1 = new Button();
            this.bu2 = new Button();
            this.bu3 = new Button();
            this.bu4 = new Button();
            this.buedit_mar = new Button();
            this.buedit_res = new Button();
            this.pb1 = new PictureBox();
            this.rbmar = new RadioButton();
            this.rbmar.Checked = true;
            this.buedit_mar.Enabled = true;
            this.buedit_res.Enabled = false;
            this.rbres = new RadioButton();
            this.rbvar = new RadioButton();
            this.rbvar.Enabled = false;
            this.lbres_mean = new Label();
            this.lbres_stdev = new Label();
            this.lbres = new Label();
            ((System.ComponentModel.ISupportInitialize)(this.axMap1)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.pMessage)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.pProgressBar)).BeginInit();
            this.panel1.SuspendLayout();
			this.panel2.SuspendLayout();
            this.panel3.SuspendLayout();
            this.SuspendLayout();
            
            // 
            // menuStrip1
            // 
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripMenuItem1,
            this.labelsToolStripMenuItem,
            //this.aboutToolStripMenuItem,
            this.helpToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Padding = new System.Windows.Forms.Padding(8, 2, 0, 2);
            this.menuStrip1.Size = new System.Drawing.Size(1381, 28);
            this.menuStrip1.TabIndex = 0;
            this.menuStrip1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top)
                | System.Windows.Forms.AnchorStyles.Left));
            this.menuStrip1.Text = "menuStrip1";
            // 
            // toolStripMenuItem1
            //
            if (resWorkflow)
            {
                this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.openToolStripMenuItem,
            this.saveToolStripMenuItem,
            this.saveAsToolStripMenuItem,
            this.exitToolStripMenuItem});
                //this.newToolStripMenuItem,
                //this.exitToolStripMenuItem});
                this.toolStripMenuItem1.Name = "toolStripMenuItem1";
                this.toolStripMenuItem1.Size = new System.Drawing.Size(44, 24);
                this.toolStripMenuItem1.Text = "File";
                this.toolStripMenuItem1.AutoToolTip = false;
                this.toolStripMenuItem1.MouseHover += new EventHandler(tSMenuItemMouseHover);
                // 
                // openToolStripMenuItem
                // 
                this.openToolStripMenuItem.Name = "openToolStripMenuItem";
                this.openToolStripMenuItem.Size = new System.Drawing.Size(129, 24);
                this.openToolStripMenuItem.Text = "Open";
                this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
                // 
                // saveToolStripMenuItem
                // 
                this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
                this.saveToolStripMenuItem.Size = new System.Drawing.Size(129, 24);
                this.saveToolStripMenuItem.Text = "Save";
                this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
                // 
                // saveAsToolStripMenuItem
                // 
                this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
                this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(129, 24);
                this.saveAsToolStripMenuItem.Text = "Save As";
                this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click);
                // 
                // exitToolStripMenuItem
                // 
                this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
                this.exitToolStripMenuItem.Size = new System.Drawing.Size(129, 24);
                this.exitToolStripMenuItem.Text = "Exit";
                this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
            }
            // 
            // labelsToolStripMenuItem
            //
            if (resWorkflow || se.MapType == Constants.MAP_RES_KRIG || se.MapType == Constants.MAP_Z_WELL)
            {
                this.labelsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.labelerToolStripMenuItem});
                this.labelsToolStripMenuItem.Name = "labelsToolStripMenuItem";
                this.labelsToolStripMenuItem.Size = new System.Drawing.Size(67, 24);
                this.labelsToolStripMenuItem.Text = "Labels";
                // 
                // labelerToolStripMenuItem
                // 
                this.labelerToolStripMenuItem.Name = "labelerToolStripMenuItem";
                this.labelerToolStripMenuItem.Size = new System.Drawing.Size(173, 24);
                this.labelerToolStripMenuItem.Text = "Labeler";
                this.labelerToolStripMenuItem.Click += new System.EventHandler(this.labelerToolStripMenuItem_Click);
            }
            if (resWorkflow)
            {
                this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.helperToolStripMenuItem,});
                //this.newToolStripMenuItem,
                //this.exitToolStripMenuItem});
                this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
                this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 24);
                this.helpToolStripMenuItem.Text = "Help";
                // 
                // openToolStripMenuItem
                // 
                this.helperToolStripMenuItem.Name = "helperToolStripMenuItem";
                this.helperToolStripMenuItem.Size = new System.Drawing.Size(129, 24);
                this.helperToolStripMenuItem.Text = "Online Documentation";
                this.helperToolStripMenuItem.Click += new System.EventHandler(this.onLineDocumentationToolStripMenuItem1_Click);
            }
            // 
            // 
			// legend1
			// 
			this.legend1.BackColor = System.Drawing.Color.White;
			this.legend1.Dock = System.Windows.Forms.DockStyle.Fill;
			this.legend1.Location = new System.Drawing.Point(24, 0);
            //this.legend1.Location = new System.Drawing.Point(24, 35);
            this.legend1.Map = null;
			this.legend1.Name = "legend1";
			this.legend1.SelectedColor = System.Drawing.Color.FromArgb(((System.Byte)(240)), ((System.Byte)(240)), ((System.Byte)(240)));
			this.legend1.SelectedLayer = -1;
			//this.legend1.Size = new System.Drawing.Size(192, 476);
            this.legend1.Size = new System.Drawing.Size(192, 276);
            this.legend1.TabIndex = 0;
			this.legend1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.legend1_MouseDown);
			this.legend1.LayerSelected += new LegendControl.LayerSelected(this.legend1_LayerSelected);
			this.legend1.GroupMouseDown += new LegendControl.GroupMouseDown(this.legend1_GroupMouseDown);
			// 
			// axMap1
			//
            this.axMap1.ContainingControl = this;
			this.axMap1.Dock = System.Windows.Forms.DockStyle.Fill;
			this.axMap1.Enabled = true;
			this.axMap1.Location = new System.Drawing.Point(219, 0);
            //this.axMap1.Location = new System.Drawing.Point(219, 35); 
            this.axMap1.Name = "axMap1";
// This caused crash
//			this.axMap1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMap1.OcxState")));
			this.axMap1.Size = new System.Drawing.Size(555, 450);
			this.axMap1.TabIndex = 1;
            this.axMap1.MouseMoveEvent += new AxMapWinGIS._DMapEvents_MouseMoveEventHandler(this.axMap1_MouseMove);
            // 
			// toolBar1
			// 
			this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
			this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
// Remove not usefull buttons MvR 13/01/2012
//																						this.tbAdd,
//																						this.tbRemove,
//																						this.tbClear,
																						this.tbZoomIn,
																						this.tbZoomOut,
																						this.tbFullExtents,
																						this.tbPan});
			this.toolBar1.DropDownArrows = true;
			this.toolBar1.ImageList = this.imageList1;
			this.toolBar1.Location = new System.Drawing.Point(0, 0);
			this.toolBar1.Name = "toolBar1";
			this.toolBar1.ShowToolTips = true;
			this.toolBar1.Size = new System.Drawing.Size(752, 28);
			this.toolBar1.TabIndex = 2;
			this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
			// 
			// tbAdd
			// 
			this.tbAdd.ImageIndex = 0;
			this.tbAdd.Tag = "Add";
			this.tbAdd.ToolTipText = "Add Layer";
			// 
			// tbRemove
			// 
			this.tbRemove.ImageIndex = 7;
			this.tbRemove.Tag = "Remove";
			this.tbRemove.ToolTipText = "Remove Layer";
			// 
			// tbClear
			// 
			this.tbClear.ImageIndex = 1;
			this.tbClear.Tag = "Clear";
			this.tbClear.ToolTipText = "Clear Layers";
			// 
			// tbZoomIn
			// 
			this.tbZoomIn.ImageIndex = 9;
			this.tbZoomIn.Tag = "ZoomIn";
			this.tbZoomIn.ToolTipText = "Zoom In";
			// 
			// tbZoomOut
			// 
			this.tbZoomOut.ImageIndex = 10;
			this.tbZoomOut.Tag = "ZoomOut";
            //this.tbZoomOut.Tag = "Identifier";
			this.tbZoomOut.ToolTipText = "Zoom Out";
			// 
			// tbFullExtents
			// 
			this.tbFullExtents.ImageIndex = 8;
			this.tbFullExtents.Tag = "FullExtents";
			this.tbFullExtents.ToolTipText = "Zoom to Fullextents";
			// 
			// tbPan
			// 
			this.tbPan.ImageIndex = 2;
			this.tbPan.Tag = "Pan";
			this.tbPan.ToolTipText = "Pan";
			// 
			// imageList1
			// 
			this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
//			this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
			this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
            // Get all the icon files in the current directory.
            // Create an Image object for each file and add it to the ImageList.
            // You can also use an Image subclass (like Icon).
            string[] iconFiles = Directory.GetFiles(Application.StartupPath+"\\Icons", "*.ico");
            SortedList<string,string> iconSl = new SortedList<string,string>();
            foreach (string iconFile in iconFiles)
            {
                iconSl.Add(iconFile, iconFile);
            }
            foreach (string iconFile in iconSl.Keys)
            {
                Icon newIcon = new Icon(iconFile);
                this.imageList1.Images.Add(newIcon);
            }
            
            
            
            
            // 
			// statusBar1
			// 
			this.statusBar1.Location = new System.Drawing.Point(0, 610);
			this.statusBar1.Name = "statusBar1";
			this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
																						  this.pMessage,
																						  this.pProgressBar});
			this.statusBar1.ShowPanels = true;
			this.statusBar1.Size = new System.Drawing.Size(752, 22);
			this.statusBar1.TabIndex = 3;
			this.statusBar1.Text = "statusBar1";
            
			// 
			// pMessage
			// 
			this.pMessage.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
			this.pMessage.Width = 368;
			// 
			// pProgressBar
			// 
			this.pProgressBar.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
			this.pProgressBar.Width = 375;
			// 
			// progressBar1
			// 
			this.progressBar1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.progressBar1.Location = new System.Drawing.Point(375, 610);
			this.progressBar1.Name = "progressBar1";
			this.progressBar1.Size = new System.Drawing.Size(368, 24);
			this.progressBar1.TabIndex = 4;
			// 
			// panel1
			// 
			this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
            this.panel1.Controls.Add(this.axMap1);
			this.panel1.Controls.Add(this.splitter1);
			this.panel1.Controls.Add(this.panel2);
			//this.panel1.Location = new System.Drawing.Point(0, 28);
            this.panel1.Location = new System.Drawing.Point(0, 56);
            this.panel1.Name = "panel1";
			//this.panel1.Size = new System.Drawing.Size(748, 476);
            this.panel1.Size = new System.Drawing.Size(748, 450);
			this.panel1.TabIndex = 5;
			// 
			// contextMenu1
			// 
			this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						 this.menuAddGroup,
																						 this.menuRemoveGroup,
																						 this.menuItem1,
																						 this.menuRenameGroup,
																						 this.menuRenameLayer,
																						 this.menuItem3,
																						 this.menuExpandGroup,
																						 this.menuCollapseGroup,
																						 this.menuExpandAll,
																						 this.menuCollapseAll});
			// 
			// menuAddGroup
			// 
			this.menuAddGroup.Index = 0;
			this.menuAddGroup.Text = "Add Group";
			this.menuAddGroup.Click += new System.EventHandler(this.menuAddGroup_Click);
			// 
			// menuRemoveGroup
			// 
			this.menuRemoveGroup.Index = 1;
			this.menuRemoveGroup.Text = "Remove Group";
			this.menuRemoveGroup.Click += new System.EventHandler(this.menuRemoveGroup_Click);
			// 
			// menuItem3
			// 
			this.menuItem3.Index = 5;
			this.menuItem3.Text = "-";
			// 
			// menuExpandGroup
			// 
			this.menuExpandGroup.Index = 6;
			this.menuExpandGroup.Text = "Expand Group";
			this.menuExpandGroup.Click += new System.EventHandler(this.menuExpandGroup_Click);
			// 
			// menuExpandAll
			// 
			this.menuExpandAll.Index = 8;
			this.menuExpandAll.Text = "Expand All";
			this.menuExpandAll.Click += new System.EventHandler(this.menuExpandAll_Click);
			// 
			// menuCollapseGroup
			// 
			this.menuCollapseGroup.Index = 7;
			this.menuCollapseGroup.Text = "Collapse Group";
			this.menuCollapseGroup.Click += new System.EventHandler(this.menuCollapseGroups_Click);
			// 
			// menuCollapseAll
			// 
			this.menuCollapseAll.Index = 9;
			this.menuCollapseAll.Text = "Collapse All";
			this.menuCollapseAll.Click += new System.EventHandler(this.menuCollapseAll_Click);
			// 
			// menuRenameGroup
			// 
			this.menuRenameGroup.Index = 3;
			this.menuRenameGroup.Text = "Rename Group";
			this.menuRenameGroup.Click += new System.EventHandler(this.menuRenameGroup_Click);
			// 
			// menuRenameLayer
			// 
			this.menuRenameLayer.Index = 4;
			this.menuRenameLayer.Text = "Rename Layer";
			this.menuRenameLayer.Click += new System.EventHandler(this.menuRenameLayer_Click);
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 2;
			this.menuItem1.Text = "-";
			// 
			// toolBar2
			// 
			this.toolBar2.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
			this.toolBar2.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
																						this.tbMoveGroupDown,
																						this.tbMoveGroupUp,
																						this.tbSetGroupIcon,
																						this.tbSetLayerIcon});
			this.toolBar2.Divider = false;
			this.toolBar2.Dock = System.Windows.Forms.DockStyle.Left;
			this.toolBar2.DropDownArrows = true;
			this.toolBar2.ImageList = this.imageList1;
			this.toolBar2.Location = new System.Drawing.Point(0, 0);
			this.toolBar2.Name = "toolBar2";
			this.toolBar2.ShowToolTips = true;
			this.toolBar2.Size = new System.Drawing.Size(24, 476);
			this.toolBar2.TabIndex = 3;
			this.toolBar2.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar2_ButtonClick);
	        // 
			// tbMoveGroupDown
			// 
			this.tbMoveGroupDown.ImageIndex = 5;
			this.tbMoveGroupDown.Tag = "MoveGroupDown";
			this.tbMoveGroupDown.ToolTipText = "Move Group Down";
			// 
			// tbMoveGroupUp
			// 
			this.tbMoveGroupUp.ImageIndex = 6;
			this.tbMoveGroupUp.Tag = "MoveGroupUp";
			this.tbMoveGroupUp.ToolTipText = "Move Group Up";
			// 
			// panel2
			// 
			this.panel2.Controls.Add(this.legend1);
            // Remove not usefull toolbar2 MvR 13/01/2012
			//this.panel2.Controls.Add(this.toolBar2);
			this.panel2.Dock = System.Windows.Forms.DockStyle.Left;
			this.panel2.Location = new System.Drawing.Point(0, 0);
			this.panel2.Name = "panel2";
			this.panel2.Size = new System.Drawing.Size(216, 476);
			this.panel2.TabIndex = 4;
			// 
			// splitter1
			// 
			this.splitter1.Location = new System.Drawing.Point(216, 0);
			this.splitter1.Name = "splitter1";
			this.splitter1.Size = new System.Drawing.Size(3, 476);
			this.splitter1.TabIndex = 5;
			this.splitter1.TabStop = false;
			// 
			// tbSetGroupIcon
			// 
			this.tbSetGroupIcon.ImageIndex = 4;
			this.tbSetGroupIcon.Tag = "SetGroupIcon";
			this.tbSetGroupIcon.ToolTipText = "Set Group Icon";
			// 
			// tbSetLayerIcon
			// 
			this.tbSetLayerIcon.ImageIndex = 3;
			this.tbSetLayerIcon.Tag = "SetLayerIcon";
			this.tbSetLayerIcon.ToolTipText = "Set Layer Icon";
            //
            // Button Contours
            //
            bu1.Location = new Point(10, 20);
            bu1.Size = new Size(80, 35);
            bu1.Text = "Create\nContourlines";
            bu1.Click += new EventHandler(bu1_Click);
            //
            // Button Save xyz
            //
            bu2.Location = new Point(100, 20);
            bu2.Size = new Size(80, 35);
            bu2.Text = "Save as\nxyz file";
            bu2.Click += new EventHandler(bu2_Click);
            //
            // Button Histogram Color chooser
            //
            bu3.Location = new Point(100, 65);
            bu3.Size = new Size(80, 35);
            bu3.Text = "Histogram\nColor scheme";
            bu3.Click += new EventHandler(bu3_Click);
            //
            // Button Grid Calculator
            //
            bu4.Location = new Point(10, 65);
            bu4.Size = new Size(80, 35);
            bu4.Text = "Grid\nCalculator";
            bu4.Click += new EventHandler(bu4_Click);
            //
            // Label res workflow
            //
            lbres.Location = new Point(0, 330);
            lbres.Size = new Size(200, 15);
            lbres.Text = "----------- Residual Workflow -------------";
            lbres.TextAlign = ContentAlignment.MiddleCenter;
            // 
            // Button edit markers
            //
            buedit_mar.Location = new Point(160, 345);
            buedit_mar.Size = new Size(30, 18);
            buedit_mar.Text = "Edit";
            Font f1 = new Font(FontFamily.GenericSerif, 7.0f);
            buedit_mar.Font = f1; 
            buedit_mar.Click += new EventHandler(buedit_mar_Click);
            // 
            // Button edit residuals
            //
            buedit_res.Location = new Point(160, 368);
            buedit_res.Size = new Size(30, 18);
            buedit_res.Text = "Edit";
            Font f2 = new Font(FontFamily.GenericSerif,7.0f);
            buedit_res.Font = f2; 
            buedit_res.Click += new EventHandler(buedit_res_Click);
            ////
            // Radio Button Markers
            //
            rbmar.Location = new Point (20, 345);
            rbmar.Size = new Size(140, 20);
            rbmar.Text = "Depths Markers";
            rbmar.TextAlign = ContentAlignment.BottomLeft;
            rbmar.CheckedChanged += new EventHandler(rbmar_CheckedChanged);
            //
            // Radio Button Residuals
            //
            rbres.Location = new Point(20, 365);
            rbres.Size = new Size(140, 20);
            rbres.Text = "Depths Residuals";
            rbres.TextAlign = ContentAlignment.BottomLeft;
            rbres.CheckedChanged += new EventHandler(rbres_CheckedChanged);
            //
            // Radio Button Variogram
            //
            rbvar.Location = new Point(20, 385);
            rbvar.Size = new Size(140, 20);
            rbvar.Text = "Variogram and Kriging";
            rbvar.TextAlign = ContentAlignment.BottomLeft;
            rbvar.CheckedChanged += new EventHandler(rbvar_CheckedChanged);
            //
            // Label res mean
            //
            lbres_mean.Location = new Point(0, 420);
            lbres_mean.Size = new Size(200, 15);
            lbres_mean.Text = "DUMMY MEAN";
            lbres_mean.TextAlign = ContentAlignment.BottomLeft;
            Font f3 = new Font(FontFamily.GenericSerif, 10.0f);
            lbres_mean.Font = f3; 
            lbres_mean.Visible = false;
            //
            // Label res stdev
            //
            lbres_stdev.Location = new Point(0, 435);
            lbres_stdev.Size = new Size(200, 15);
            lbres_stdev.Text = "DUMMY STDEV";
            lbres_stdev.TextAlign = ContentAlignment.MiddleLeft;
            lbres_stdev.Font = f3;
            lbres_stdev.Visible = false;
            
            //
            // Trackbar 1 (LightIntensity)
            //
            lb1.Location = new Point(610,0);
            lb1.Size = new Size(30,15);
            lb1.Text = "Int";
            lb1.TextAlign = ContentAlignment.MiddleCenter;
            trb1.Location = new Point(610, 15);
            trb1.Size = new Size(15, 60);
            trb1.Orientation = Orientation.Vertical;
            trb1.SetRange(0, 100);
            trb1.Value = 50;
            trb1.TickFrequency = 10;
            trb1.Name = "LightIntensity";
            trb1.ValueChanged += new EventHandler(trb1_ValueChanged);
            ToolTip trb1TT = new ToolTip();
            trb1TT.SetToolTip(trb1, "Light source intensity");
            //trb1TT.AutomaticDelay = 2000;
            //trb1TT.ShowAlways = true;
            //trb1TT.InitialDelay = 1;
            //
            // Trackbar 2 (LightAzimuth)
            //
            lb2.Location = new Point(660, 0);
            lb2.Size = new Size(30, 15);
            lb2.Text = "Azi";
            lb2.TextAlign = ContentAlignment.MiddleCenter;
            trb2.Location = new Point(660, 15);
            trb2.Size = new Size(15, 60);
            trb2.Orientation = Orientation.Vertical;
            trb2.SetRange(0,100);
            trb2.Value = 50;
            trb2.TickFrequency = 10;
            trb2.Name = "LightAzimuth";
            trb2.ValueChanged += new EventHandler(trb1_ValueChanged);
            ToolTip trb2TT = new ToolTip();
            trb2TT.SetToolTip(trb2, "Light source azimuth range -180->180 degrees");
            //trb2TT.AutomaticDelay = 2000;
            //trb2TT.ShowAlways = true;
            //trb2TT.ToolTipIcon = ToolTipIcon.None;
            //trb2TT.InitialDelay = 1;
            //
            // Trackbar 2 (LightElevation)
            //
            lb3.Location = new Point(710, 0);
            lb3.Size = new Size(30, 15);
            lb3.Text = "Elev";
            lb3.TextAlign = ContentAlignment.MiddleCenter;
            trb3.Location = new Point(710, 15);
            trb3.Size = new Size(15,60);
            trb3.Orientation = Orientation.Vertical;
            trb3.SetRange(0, 90);
            trb3.Value = 50;
            trb3.TickFrequency = 10;
            trb3.Name = "LightElevation";
            trb3.ValueChanged += new EventHandler(trb1_ValueChanged);
            ToolTip trb3TT = new ToolTip();
            trb3TT.SetToolTip(trb3, "Light Source elevation range 0-90 degrees");
            //trb3TT.AutomaticDelay = 2000;
            //trb3TT.ShowAlways = true;
            //trb3TT.ToolTipIcon = ToolTipIcon.None;
            //trb3TT.InitialDelay = 1;
            //
            // Colour Combobox cb1
            //
            lb4.Location = new Point(600, 80);
            lb4.Size = new Size(40, 15);
            lb4.Text = "Colors";
            lb4.TextAlign = ContentAlignment.MiddleCenter;
            cb1.Location = new Point(650, 80);
            cb1.Size = new Size(100, 20);
            cb1.Text = "Colour Scheme";
            cb1.Items.Add("Rainbow");
            cb1.Items.Add("SummerMountains");
            cb1.Items.Add("DeadSea");
            cb1.Items.Add("Desert");
            cb1.Items.Add("FallLeaves");
            cb1.Items.Add("Glaciers");
            cb1.Items.Add("ValleyFires");
            if (resWorkflow)
            {
                cb1.SelectedIndex = 3;
            }
            else
            {
                cb1.SelectedIndex = 0;
            }
            cb1.SelectedIndexChanged += new EventHandler(cb1_ValueChanged);
            //
            // Picture box 1
            //
            pb1.Location = new Point(200,20);
            pb1.Size = new Size(400,110);
            pb1.BorderStyle = BorderStyle.None;
            this.pb1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pb1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.pb1.MouseMove += new MouseEventHandler(pb1_MouseMove);
            this.pb1.MouseDown += new MouseEventHandler(pb1_MouseDown);
            this.pb1.MouseUp += new MouseEventHandler(pb1_MouseUp);
            //
            // Label grid
            //
            lbgrid.Location = new Point(0 , 0);
            lbgrid.Size = new Size(600, 20);
            lbgrid.Text = "---------------------------------------------------------------------- Grid functions ----------------------------------------------------------->";
            lbgrid.TextAlign = ContentAlignment.MiddleCenter;// 
            // panel3
            // 
            this.panel3.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.panel3.Location = new System.Drawing.Point(0, 506);
            this.panel3.Name = "panel3";
            this.panel3.MouseMove += new MouseEventHandler(panel3_MouseMove);
            //this.panel3.Size = new System.Drawing.Size(752, 90);
            this.panel3.Size = new System.Drawing.Size(752,130);
            this.panel3.BorderStyle = BorderStyle.None;
            this.panel3.TabIndex = 4;
            this.panel3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.panel3.Controls.Add(this.lb1);
            this.panel3.Controls.Add(this.lb2);
            this.panel3.Controls.Add(this.lb3);
            this.panel3.Controls.Add(this.trb1);
            this.panel3.Controls.Add(this.trb2);
            this.panel3.Controls.Add(this.trb3);
            this.panel3.Controls.Add(this.lb4);
            this.panel3.Controls.Add(this.cb1);
            this.panel3.Controls.Add(this.bu1);
            /*if (se.MapType == Constants.MAP_Z ||
                se.MapType == Constants.MAP_ZDEV ||
                se.MapType == Constants.MAP_Z_WELL ||
                se.MapType == Constants.MAP_ZDEV_WELL)
            {*/
            this.panel3.Controls.Add(this.bu2);
            this.panel3.Controls.Add(this.bu3);
            if (bgridcalc)
            {
                this.panel3.Controls.Add(this.bu4);
            }
            this.panel3.Controls.Add(this.pb1);
            this.panel3.Controls.Add(this.lbgrid);
            //
            if (resWorkflow)
            {
                this.legend1.Controls.Add(this.lbres);
                this.legend1.Controls.Add(this.buedit_mar);
                this.legend1.Controls.Add(this.buedit_res);
                this.legend1.Controls.Add(this.rbmar);
                this.legend1.Controls.Add(this.rbres);
                this.legend1.Controls.Add(this.rbvar);
                this.legend1.Controls.Add(this.lbres_mean);
                this.legend1.Controls.Add(this.lbres_stdev);
                //this.legend1.Controls.Add(this.rbresmap);
                //this.legend1.Controls.Add(this.rbavzmap);
            }
            else
            {
                this.legend1.Controls.Add(this.lbres_mean);
                this.legend1.Controls.Add(this.lbres_stdev);
            }
                
            /*}*/
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			//this.ClientSize = new System.Drawing.Size(752, 582);
            this.ClientSize = new System.Drawing.Size(752, 632);
            this.Controls.Add(this.panel1);
			this.Controls.Add(this.toolBar1);
            this.Controls.Add(this.progressBar1);
			this.Controls.Add(this.statusBar1);
            this.Controls.Add(this.panel3);
            this.Controls.Add(this.menuStrip1);
            
            
			this.Name = "Form1";
//			this.Text = "Legend Sample Project";
            this.Load += new EventHandler(FormMap_Load);
			this.Resize += new System.EventHandler(this.Form1_Resize);
			((System.ComponentModel.ISupportInitialize)(this.axMap1)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.pMessage)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.pProgressBar)).EndInit();
			this.panel1.ResumeLayout(false);
			this.panel2.ResumeLayout(false);
            this.panel3.ResumeLayout(false);
			this.ResumeLayout(false);
            

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
        [STAThread]

        //		static void Main() 
        //		{
        //			Application.Run(new Form1());
        //		}

        #region component callbacks
        // Radiobuttons checked changed
        private void rbmar_CheckedChanged(Object sender, EventArgs e)
        {
            // Close table editor
            if (te1 != null){ te1.Close();}
            if (rbmar.Checked)
            {
                 // convert shpfile_open from resid to markers
                if ((rwf_phase == Constants.RWF_PHASE_RESID || rwf_phase == Constants.RWF_PHASE_VARIOGRAM)
                    && shpfile_opened )
                {
                   
                
                    try
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        double x = 0.0, y = 0.0, zo = 0.0, z = 0.0, v = 0.0; ;
                        int nx, ny;
                        shpfile_open.StartEditingTable(null);
                        for (int i = 0; i < shpfile_open.NumShapes; i++)
                        {
                            shpfile_open.get_Shape(i).get_XY(0, ref x, ref y);
                            zo = (double)shpfile_open.get_CellValue(0, i);
                            z = (double)shpfile_open.get_CellValue(1, i);
                            grid.ProjToCell(x, y, out nx, out ny);
                            v = Convert.ToDouble(grid.get_Value(nx, ny));
                            shpfile_open.EditCellValue(0, i, zo + v);
                            if (z < Constants.SHP_NODATA)
                            {
                                shpfile_open.EditCellValue(1, i, z + v);
                            }
                            else
                            {
                                shpfile_open.EditCellValue(1, i, Constants.SHP_NODATA);
                            }
                        }
                        legend1.Refresh();
                        shpfile_open.StartEditingTable(null);
                        shpfile_open.Save(null);
                        rwf_phase = Constants.RWF_PHASE_MARKERS;
                        se.Rwf_phase = rwf_phase; 
                        legend1.Layers.Remove(handle_depth);
                        AddLayer(shpfilename_open, false, false);
                        openToolStripMenuItem.Enabled = true;
                        if (se.File_rwf_phase == se.Rwf_phase)
                        {
                            saveToolStripMenuItem.Enabled = true;
                        }
                        else
                        {
                            saveToolStripMenuItem.Enabled = false;
                        }
                        saveAsToolStripMenuItem.Enabled = true;
                        rbvar.Enabled = false;
                        Cursor.Current = Cursors.Default;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("**ERROR Creating Residual file from Marker file**\n" + ex.Message);
                    }
                }
                buedit_mar.Enabled = true;
                buedit_res.Enabled = false;
                
            }
        }
        
        private void rbres_CheckedChanged(Object sender, EventArgs e)
        {
            // close table editor
            if (te1 != null) { te1.Close(); }
            // convert shpfile_open from marker to residual
                
            if (rbres.Checked)
            {
                //MessageBox.Show(shpfile_open.NumShapes.ToString());
                if (rwf_phase == Constants.RWF_PHASE_MARKERS && shpfile_opened)
                {
                    try
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        // save markers for display in avzmap
                        shpfilename_mar = se.TempFolderpath + Guid.NewGuid().ToString() + ".shp";
                        se.Shpfilename_mar = shpfilename_mar;
                        shpfile_mar = new MapWinGIS.Shapefile();
                        shpfile_mar.Open(shpfilename_open, null);
                        shpfile_mar.SaveAs(shpfilename_mar, null);
                    
                        shpfile_open.StartEditingTable(null);
                                             
                        double x = 0.0, y = 0.0, zo = 0.0, z = 0.0, v = 0.0; ;
                        int nx, ny;
                        for (int i = 0; i < shpfile_open.NumShapes; i++)
                        {
                            shpfile_open.get_Shape(i).get_XY(0, ref x, ref y);
                            zo = (double)shpfile_open.get_CellValue(0, i);
                            z = (double)shpfile_open.get_CellValue(1, i);
                            grid.ProjToCell(x, y, out nx, out ny);
                            v = Convert.ToDouble(grid.get_Value(nx, ny));
                            shpfile_open.EditCellValue(0, i, zo - v);
                            if (z < Constants.SHP_NODATA)
                            {
                                shpfile_open.EditCellValue(1, i, z - v);
                            }
                            else
                            {
                                shpfile_open.EditCellValue(1, i, Constants.SHP_NODATA);
                            }
                        }
                        legend1.Refresh();
                        shpfile_open.StartEditingShapes(true,null);
                        shpfile_open.Save(null);
                        rwf_phase = Constants.RWF_PHASE_RESID;
                        se.Rwf_phase = rwf_phase; 
                        legend1.Layers.Remove(handle_depth);
                        AddLayer(shpfilename_open, false, false);
                        openToolStripMenuItem.Enabled = true;
                        if (se.File_rwf_phase == se.Rwf_phase)
                        {
                            saveToolStripMenuItem.Enabled = true;
                        }
                        else
                        {
                            saveToolStripMenuItem.Enabled = false;
                        } 
                        saveAsToolStripMenuItem.Enabled = true;
                        rbvar.Enabled = true;
                        Cursor.Current = Cursors.Default;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("**ERROR Creating Residual file from Marker file**\n" + ex.Message);
                    }
                }
                else if (rwf_phase == Constants.RWF_PHASE_VARIOGRAM && shpfile_opened)
                {
                    rwf_phase = Constants.RWF_PHASE_RESID;
                    se.Rwf_phase = rwf_phase;
                    if (se.File_rwf_phase == Constants.RWF_PHASE_RESID)
                    {
                        saveToolStripMenuItem.Enabled = true;
                    }
                    else
                    {
                        saveToolStripMenuItem.Enabled = false;
                    }
                    saveAsToolStripMenuItem.Enabled = true;
                    rbvar.Enabled = true;
                }
                else
                {
                    rwf_phase = Constants.RWF_PHASE_RESID;
                    se.Rwf_phase = rwf_phase; 
                }
                buedit_res.Enabled = true;
                buedit_mar.Enabled = false;
            }
        }
        
        private void rbvar_CheckedChanged(Object sender, EventArgs e)
        {
            if (rbvar.Checked)
            {
                double z = 0.0;
                int numpoints = 0;
                for (int i = 0; i < shpfile_open.NumShapes; i++)
                {
                    z = (double)shpfile_depth.get_CellValue(1, i);
                    if (z < Constants.SHP_NODATA)
                    {
                        numpoints++;
                    }
                }
                if (numpoints < 3)
                {
                    MessageBox.Show("Number of residuals<3, kriging not possible");
                    rbres.Checked = true;
                }
                else
                {
                    buedit_res.Enabled = false;
                    buedit_mar.Enabled = false;
                    rwf_phase = Constants.RWF_PHASE_VARIOGRAM;
                    saveToolStripMenuItem.Enabled = false;
                    saveAsToolStripMenuItem.Enabled = false;
                    se.Rwf_phase = rwf_phase;
                    Select sl1 = new Select(sd, shpfile_open, ref se);
                    sl1.Show();
                }
            }
        }
        
        
        
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (te1 != null) { te1.Close(); }
            OpenFileDialog of1 = new OpenFileDialog();
            se.ErrorMessage = null;
            of1.Filter = "Tab/Space delimited depth files|*.*";
            of1.FilterIndex = 1;
            var mb_ret = of1.ShowDialog();
            switch (mb_ret)
            {
                case DialogResult.Cancel:
                    break;
                default:
                    se.TempFolderpath = Path.GetTempPath();
                    shpfile_open2 = new MapWinGIS.ShapefileClass();
                    XYPointFile xyf1 = new XYPointFile();
                    shpfile_open2 = xyf1.file2Shape(of1.FileName, ref se);
                    if (se.ErrorMessage != null)
                    {
                        MessageBox.Show(this, se.ErrorMessage, "**Error**",
                        MessageBoxButtons.OK);
                        break;
                    }
                    shpfile_open = new MapWinGIS.ShapefileClass();
                    shpfile_open = shpfile_open2;
                    filename_open = of1.FileName;
                    this.Text = formText + " depthfile=" + filename_open;
                    shpfilename_open = se.TempFolderpath + Guid.NewGuid().ToString() + ".shp";
                    se.Shpfilename_open = shpfilename_open;
                    shpfile_open.SaveAs(shpfilename_open, null);
                    if (handle_depth > -1) { legend1.Layers.Remove(handle_depth); }    
                    AddLayer(shpfilename_open, false, false);
                    shpfile_opened = true;
                    saveToolStripMenuItem.Enabled = true;
                    saveAsToolStripMenuItem.Enabled = true;
                    if (rwf_phase == Constants.RWF_PHASE_RESID) 
                    {
                        rbvar.Enabled = true;
                    }
                    break;
            }
        }
        
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            XYPointFile xyf1 = new XYPointFile();
            xyf1.shape2File(shpfile_open, filename_open, ref se);
            if (se.ErrorMessage != null)
            {
                MessageBox.Show(this, se.ErrorMessage, "Error Occurred",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                return;
            }
        }

        // Method for Save As dialog (Menubaroption File->Save As)
        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sf1 = new SaveFileDialog();
            sf1.Filter = "Depth files|*.*";
            sf1.FilterIndex = 1;
            var mb_ret = sf1.ShowDialog();
            switch (mb_ret)
            {
                case DialogResult.Cancel:
                    break;
                default:
                    // Save File
                    XYPointFile xyf1 = new XYPointFile();
                    xyf1.shape2File(shpfile_open, sf1.FileName, ref se);                   
                    if (se.ErrorMessage != null)
                    {
                        MessageBox.Show(this, se.ErrorMessage, "Error Occurred",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        filename_open = sf1.FileName;
                        this.Text = formText + " depthfile=" + filename_open;
                        saveToolStripMenuItem.Enabled = true;
                        saveAsToolStripMenuItem.Enabled = true;
                    }
                    break;
            }

        }
        
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tSMenuItemMouseHover(object sender, EventArgs e)
        {
            ToolStripMenuItem mItem = (ToolStripMenuItem)sender;
            tt2.InitialDelay = 1;
            tt2.Show("Open,Save depthfile , format (x y depth wellname(no spaces)) or\ndepth(marker or residual) file saved previously in workflow",
            mItem.Owner, 6000);
        }            
        
        // Start labeler for labeler toolstrip item
        private void labelerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            shpfile_depth.Labels.Clear();
            frmLabelStyle fmstyl1 = new frmLabelStyle(shpfile_depth, legend1, axMap1, handle_depth, se);
            fmstyl1.ShowDialog();
            
        }

        private void onLineDocumentationToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("chrome.exe", "www.velsto.org/downloads/Velsto_User_Instructions_121.pdf");
            }
            catch (Exception ex)
            {
                try
                {
                    System.Diagnostics.Process.Start("iexplore.exe", "www.velsto.org/downloads/Velsto_User_Instructions_121.pdf");

                }
                catch (Exception ex2)
                {
                    MessageBox.Show("Need Chrome or Internet Explorer to view documentation this way \n" +
                                    "available as www.velsto.org/downloads/Velsto_User_Instructions_121.pdf or " +
                                    "in C:\\data\\Velsto\\docs");
                }
            }
        }
        
        // Trackbar value changed
        private void cb1_ValueChanged(Object sender, EventArgs e)
        {
            // remove Map
            legend1.Layers.Remove(handle_grid);
            // redraw Map
            AddLayer(se.MapFile, false, false);
            // move depth and contour above Map
            if (handle_contour > -1)
            {
                legend1.Layers.MoveLayerWithinGroup(handle_contour, 2);
            }
            if (handle_depth > -1)
            {
                legend1.Layers.MoveLayerWithinGroup(handle_depth, 2);
            }   
            legend1.Refresh();
            if (graphCreated)
            {
                CreateGraph(true, 0.0f);
            }
                
        }
        
        private void trb1_ValueChanged(Object sender, EventArgs e)
        {
            // remove Map
            legend1.Layers.Remove(handle_grid);
            // redraw Map
            AddLayer(se.MapFile, false, false);
            // move depth and contour  above Map
            if (handle_contour > -1)
            {
                legend1.Layers.MoveLayerWithinGroup(handle_contour, 2);
            }
            if (handle_depth > -1)
            {
                legend1.Layers.MoveLayerWithinGroup(handle_depth, 2);
            }
            legend1.Refresh();
        }

        

        private void bu1_Click(Object sender, EventArgs e)
        {
            //
            // Method to create contourintervals (Mapwindow uses GDAL(gdal.org) routines).
            //
            
            
            //get contourintervals
            int nrContourIntervals = 8;
            List<double> ldCntInt;
            double[] cntInt = new double[30];
            XYPointFile xyz1 = new XYPointFile();
            ldCntInt = xyz1.getContourIntervals(nrContourIntervals, Convert.ToDouble(grid.Minimum),
                                                          Convert.ToDouble(grid.Maximum));
            FormContour fc = new FormContour(new ContourDelegate(contourCreate),
                                             ldCntInt.Count, ldCntInt[0], ldCntInt[ldCntInt.Count - 1]);
            fc.Show();
        
        }

        private void contourCreate(int contNrInt, double contMin, double contMax)
        {
            Cursor.Current = Cursors.WaitCursor;
            bool bResult;
            MapWinGIS.Utils utils;
            //save the grid to tiff for contour
            //string gridTifFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".tif";
            string gridTifFile = se.TempFolderpath + "\\" + "gridBmp.tif";
            bResult = grid.Save(gridTifFile, MapWinGIS.GridFileType.GeoTiff, this);
            if (!bResult)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Could not save grid file for contouring");
                return;
            }

            List<double> ldCntInt;
            double[] cntInt = new double[40];
            XYPointFile xyz1 = new XYPointFile();
            ldCntInt = xyz1.getContourIntervals(contNrInt, contMin, contMax);
            int maxcont = 0;
            if (ldCntInt.Count == 0)
            {
                MessageBox.Show("Unable to create contours for parameters\nChange parameters");
                return;
            }
            if (ldCntInt.Count > cntInt.Length)
            {
                maxcont = cntInt.Length;
            }
            else
            {
                maxcont = ldCntInt.Count;
            }
            for (int i=0; i<maxcont; i++)
            {
                cntInt[i] = ldCntInt[i];
            }
            for (int i2 = maxcont; i2 < cntInt.Length; i2++)
            {               
                    cntInt[i2] = ldCntInt[ldCntInt.Count - 1];
            }
            
            //create the contourshapefile
            string cntShpFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".shp";                                     
            utils = new MapWinGIS.UtilsClass();
            bResult = utils.GenerateContour(gridTifFile, cntShpFile , 0.0  , 99999.0, false, cntInt, this);
            if (!bResult)
            {
                MessageBox.Show("Create contour shape file failed");
            }
            if (handle_contour > -1)
            {
                legend1.Layers.Remove(handle_contour);
            }
            AddLayer(cntShpFile, true, false);
            Cursor.Current = Cursors.Default;
        }
        
        private void  bu2_Click(Object sender, EventArgs e)
        {
            //
            // Method to save Grid as xyz file.
            //
            SaveFileDialog sf1 = new SaveFileDialog();
            sf1.Filter = "All files|*.*";
            sf1.FilterIndex = 1;
            var mb_ret2 = sf1.ShowDialog();
            switch (mb_ret2)
            {
                case DialogResult.Cancel:
                    break;
                default:
                    TextWriter xyzFile = new StreamWriter(sf1.FileName);
                    Dictionary<Point, double> dict1 = new Dictionary<Point, double>();
                    bu2.Enabled = false;
                    Cursor.Current = Cursors.WaitCursor;
                    double x = 0.0, y = 0.0;
                    for (int nx = 0; nx < se.MapNcols; nx++)
                    {
                        for (int ny = 0; ny < se.MapNrows; ny++)
                        {                            
                            grid.CellToProj(nx, ny, out x, out y);
                            double val = 0.0;
                            val = Convert.ToDouble(grid.get_Value(nx,ny));
                            if (!val.ToString().Equals(Constants.MAP_NODATA))
                            {
                                xyzFile.WriteLine(
                                    x.ToString("0.0", CultureInfo.InvariantCulture) + " " +
                                    y.ToString("0.0", CultureInfo.InvariantCulture) + " " +
                                    val.ToString("0.0", CultureInfo.InvariantCulture));
                            }
                            else
                            {
                                //MessageBox.Show("No data");
                            }
                        }
                    }
                    xyzFile.Close();
                    Cursor.Current = Cursors.Default;
                    bu2.Enabled = true;
                    break;
            }
        }

        private void bu3_Click(Object sender, EventArgs e)
        {
            //
            // Method to create histogram and start color scheme definition.
            //
            graphCreated = false;
            CreateGraph(false, 0.0f);
        }
        
        private void bu4_Click(Object sender, EventArgs e)
        {
            //
            // Start Grid Calculator.
            //
            frmMapCalculator fm1 = new frmMapCalculator(true, se);
            fm1.Show();
        }
        private void buedit_mar_Click(Object sender, EventArgs e)
        {
            //
            // Method to start shapefile attributes editing.
            //
            if (!(rwf_phase == Constants.RWF_PHASE_MARKERS))
            {
                MessageBox.Show("This Editing function not valid for the current workflow phase.");
                return;
            }
            else if (handle_depth < 0)
            {
                MessageBox.Show("** ERROR ** No depths available\nFirst open depth file with File->Open");
                return;
            }
            else
            {
                // Open Table attribute editor
                shpfile_open.Open(shpfilename_open, null);
                TableEditorNew.BO.BOShapeData bosdata = new TableEditorNew.BO.BOShapeData(shpfile_open);
                TableEditorNew.BO.BOShapeFile bos1 = new TableEditorNew.BO.BOShapeFile();
                shpfile_open.StartEditingShapes(true, null);
                bos1.ShapeFile = shpfile_open;
                bos1.ShapefileName = "";
                te1 = new TableEditorNew.Forms.frmTableEditor(rwf_phase,bos1, new TableEditorNew.BO.BOMapWindow(new TableEditorNew.BO.BOMapWindowDelegate(set_handle_depth), axMap1, legend1, shpfilename_open, handle_depth, se));
                te1.Show();
                te1.InitForm();
            }
        }
        
        private void buedit_res_Click(Object sender, EventArgs e)
        {
            //
            // Method to start shapefile attributes editing.
            //
            if (!(rwf_phase == Constants.RWF_PHASE_RESID))
            {
                MessageBox.Show("This Editing function not valid for the current workflow phase.");
                return;
            }
            else if (handle_depth < 0)
            {
                MessageBox.Show("** ERROR ** No depths available\nFirst open depth file with File->Open");
                return;
            }
            else
            {
                // Open table attributes editor
                shpfile_open.Open(shpfilename_open, null);
                TableEditorNew.BO.BOShapeData bosdata = new TableEditorNew.BO.BOShapeData(shpfile_open);
                TableEditorNew.BO.BOShapeFile bos1 = new TableEditorNew.BO.BOShapeFile();
                shpfile_open.StartEditingShapes(true, null);
                bos1.ShapeFile = shpfile_open;
                bos1.ShapefileName = "";
                te1 = new TableEditorNew.Forms.frmTableEditor(rwf_phase,bos1, new TableEditorNew.BO.BOMapWindow(new TableEditorNew.BO.BOMapWindowDelegate(set_handle_depth), axMap1, legend1, shpfilename_open, handle_depth, se));
                te1.Show();
                te1.InitForm();
            }
        }

        private void set_handle_depth(MapWinGIS.Shapefile s1)
        {
            // callback from TableEditor to update shapes on map after Apply in TableEditor
            shpfile_open = s1;
            shpfile_open.StartEditingShapes(true, null);
            shpfile_open.Save(null);
            legend1.Layers.Remove(handle_depth);
            AddLayer(shpfilename_open, false, false); 
        }
        
        
        private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
		{
			string tag = (string)e.Button.Tag;
            switch(tag)
			{
				case "Add":
					AddLayer("", false, true);
					break;
				case "Remove":
					legend1.Layers.Remove(legend1.SelectedLayer);
					legend1.Refresh();
					break;
				case "Clear":
                    legend1.Layers.Clear();
					break;
				case "ZoomIn":
					axMap1.CursorMode = MapWinGIS.tkCursorMode.cmZoomIn;
					break;
				case "ZoomOut":
					axMap1.CursorMode = MapWinGIS.tkCursorMode.cmZoomOut;
					break;
				case "Pan":
					axMap1.CursorMode = MapWinGIS.tkCursorMode.cmPan;
                    break;
				case "FullExtents":
					axMap1.ZoomToMaxExtents();
					break;
			}
        }

		private void toolBar2_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
		{
			OpenFileDialog openDlg;
			string tag = (string)e.Button.Tag;
            int curPos;
            switch(tag)
			{
				case "MoveGroupDown":
					if(legend1.Groups.IsValidHandle(m_GroupHandle))
					{
						curPos = legend1.Groups.PositionOf(m_GroupHandle);
						legend1.Groups.MoveGroup(m_GroupHandle,curPos-1);
					}
					break;
				case "MoveGroupUp":
					if(legend1.Groups.IsValidHandle(m_GroupHandle))
					{
						curPos = legend1.Groups.PositionOf(m_GroupHandle);
						legend1.Groups.MoveGroup(m_GroupHandle,curPos+1);
					}
					break;
				case "SetGroupIcon":
					openDlg = new OpenFileDialog();
					openDlg.Filter = "Icon (*.ico)|*.ico";
					
					if(openDlg.ShowDialog(this) == DialogResult.OK)
					{
						if(legend1.Groups.IsValidHandle(m_GroupHandle))
							legend1.Groups.ItemByHandle(m_GroupHandle).Icon = new Icon(openDlg.FileName);
					}

					break;
				case "SetLayerIcon":
					openDlg = new OpenFileDialog();
					openDlg.Filter = "Icon (*.ico)|*.ico";
					
					if(openDlg.ShowDialog(this) == DialogResult.OK)
					{
						legend1.Layers.ItemByHandle(legend1.SelectedLayer).Icon = new Icon(openDlg.FileName);
						legend1.Refresh();
					}
					break;
			}

        }


        private void Form1_Resize(object sender, System.EventArgs e)
        {
            progressBar1.Location = new System.Drawing.Point(statusBar1.Panels[0].Width + 1, progressBar1.Location.Y);
            progressBar1.Width = statusBar1.Panels[1].Width;

        }


        private void legend1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            //display the context menu on a right click on the legend
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                //check to see if a layer or group has been selected
                if (legend1.Groups.IsValidHandle(m_GroupHandle))
                {
                    menuRemoveGroup.Enabled = true;
                    menuExpandGroup.Enabled = true;
                    menuCollapseGroup.Enabled = true;
                }
                else
                {
                    menuRemoveGroup.Enabled = false;
                    menuExpandGroup.Enabled = false;
                    menuCollapseGroup.Enabled = false;
                }

                //display the context menu
                contextMenu1.Show(legend1, new System.Drawing.Point(e.X, e.Y));
            }
        }

        private void menuAddGroup_Click(object sender, System.EventArgs e)
        {
            //create a new group and put in position 0
            legend1.Groups.Add("New Group");
        }

        private void menuRemoveGroup_Click(object sender, System.EventArgs e)
        {
            //remove the current group
            if (legend1.Groups.IsValidHandle(m_GroupHandle))
                legend1.Groups.Remove(m_GroupHandle);
        }

        private void menuExpandGroup_Click(object sender, System.EventArgs e)
        {
            //expand the current group
            if (legend1.Groups.IsValidHandle(m_GroupHandle))
                legend1.Groups.ItemByHandle(m_GroupHandle).Expanded = true;
        }

        private void menuExpandAll_Click(object sender, System.EventArgs e)
        {
            //expand all of the groups
            legend1.Groups.ExpandAll();
        }

        private void menuCollapseGroups_Click(object sender, System.EventArgs e)
        {
            //colapse the current group
            if (legend1.Groups.IsValidHandle(m_GroupHandle))
                legend1.Groups.ItemByHandle(m_GroupHandle).Expanded = false;
        }

        private void menuCollapseAll_Click(object sender, System.EventArgs e)
        {
            //collapse all of the groups
            legend1.Groups.CollapseAll();
        }

        private void legend1_GroupMouseDown(int Handle, System.Windows.Forms.MouseButtons button)
        {
            //save the handle of the selected group
            m_GroupHandle = Handle;
        }

        private void legend1_LayerSelected(int Handle)
        {
            //saves the group handle of the active group
            m_GroupHandle = legend1.Layers.GroupOf(Handle);
        }

        private void menuRenameGroup_Click(object sender, System.EventArgs e)
        {
            InputForm inputfrm;

            //rename the active group or selected group
            if (legend1.Groups.IsValidHandle(m_GroupHandle))
            {
                //get the user new name for the group
                inputfrm = new InputForm("Rename Group", legend1.Groups.ItemByHandle(m_GroupHandle).Text);

                if (inputfrm.ShowDialog(this) == DialogResult.OK)
                    legend1.Groups.ItemByHandle(m_GroupHandle).Text = inputfrm.InputName;
            }
        }

        private void menuRenameLayer_Click(object sender, System.EventArgs e)
        {
            InputForm inputfrm;

            //get the user new name for the group
            inputfrm = new InputForm("Rename Layer", axMap1.get_LayerName(legend1.SelectedLayer));

            if (inputfrm.ShowDialog(this) == DialogResult.OK)
            {
                axMap1.set_LayerName(legend1.SelectedLayer, inputfrm.InputName);
                legend1.Refresh();
            }

        }

        private void panel3_MouseMove(object sender, MouseEventArgs e)
        {
            this.statusBar1.Panels[0].Text = "X = " + e.X.ToString() + " Y = " + e.Y.ToString();
        }

        private void pb1_MouseMove(object sender, MouseEventArgs e)
        {
            if (graphCreated)
            {
                mouseOverLeft = false;
                mouseOverRight = false;
                float val = ((e.X - graphicHistogram.XSlice) / graphicHistogram.GraphXprop) + minD;
                if (val > 100.0 || val < -100.0)
                {
                    this.statusBar1.Panels[0].Text = "Hist X = " + val.ToString("0.0");
                }
                else
                {
                    this.statusBar1.Panels[0].Text = "Hist X = " + val.ToString();
                }
                if (mouseDownLeft || mouseDownRight)
                {
                    Cursor.Current = Cursors.VSplit;
                    if (mouseDownLeft)
                    {
                        if (e.X < (xRight + graphicHistogram.XSlice - 20.0))
                        {
                            CreateGraph(true, (float)e.X);
                        }
                        else
                        {
                            CreateGraph(true, xRight + graphicHistogram.XSlice - 20.0f);
                        }
                    }
                    else if (mouseDownRight)
                    {
                        if (e.X > (xLeft + graphicHistogram.XSlice + 20.0))
                        {
                            CreateGraph(true, (float)e.X);
                        }
                        else
                        {
                            CreateGraph(true, xLeft + graphicHistogram.XSlice + 20.0f);
                        }
                    }

                }
                else
                {
                    if (e.X > (xLeft + graphicHistogram.XSlice - 10.0) && e.X < (xLeft + graphicHistogram.XSlice + 10.0))
                    {
                        mouseOverLeft = true;
                        Cursor.Current = Cursors.VSplit;
                    }
                    else if (e.X > (xRight + graphicHistogram.XSlice - 10.0) && e.X < (xRight + graphicHistogram.XSlice + 10.0))
                    {
                        mouseOverRight = true;
                        Cursor.Current = Cursors.VSplit;
                    }

                }
            }
        }

        private void pb1_MouseDown(object sender, MouseEventArgs e)
        {
            if (graphCreated)
            {
                Cursor.Current = Cursors.VSplit;
                mouseDownLeft = false;
                if (mouseOverLeft) mouseDownLeft = true;
                mouseDownRight = false;
                if (mouseOverRight) mouseDownRight = true;
            }
        }

        private void pb1_MouseUp(object sender, MouseEventArgs e)
        {
            float leftReal = 0.0f;
            float rightReal = 0.0f;
            float newXprop = 0.0f;
            float newXrealValue = 0.0f;
            if (graphCreated)
            {
                if (mouseDownLeft || mouseDownRight)
                {
                    // calculate dimensions new graph
                    if (mouseDownLeft)
                    {
                        if (e.X < (xRight + graphicHistogram.XSlice - 20.0))
                        {
                            leftReal = ((e.X - graphicHistogram.XSlice) / graphicHistogram.GraphXprop) + minD;
                        }
                        else
                        {
                            leftReal = ((xRight - 20.0f) / graphicHistogram.GraphXprop) + minD;

                        }
                        rightReal = (xRight / graphicHistogram.GraphXprop) + minD;
                    }
                    else if (mouseDownRight)
                    {
                        leftReal = (xLeft / graphicHistogram.GraphXprop) + minD;
                        if (e.X > (xLeft + graphicHistogram.XSlice + 20.0))
                        {
                            rightReal = ((e.X - graphicHistogram.XSlice) / graphicHistogram.GraphXprop) + minD;
                        }
                        else
                        {
                            rightReal = ((xLeft + 20.0f) / graphicHistogram.GraphXprop) + minD;
                        }
                    }
                    if (leftReal < (float)Convert.ToDouble(grid.Minimum)) leftReal = (float)Convert.ToDouble(grid.Minimum);
                    if (rightReal > (float)Convert.ToDouble(grid.Maximum)) rightReal = (float)Convert.ToDouble(grid.Maximum);
                    newXrealValue = (float)(((rightReal - leftReal) * 50) / (xRight - xLeft));
                    //newXprop = 50 / graphicHistogram.Multip(newXrealValue);
                    newXprop = 50 / newXrealValue;
                    minD = leftReal - (xLeft / newXprop);
                    maxD = rightReal + ((graphicHistogram.Width - (2 * graphicHistogram.XSlice) - xRight) / newXprop);
                    // reset status
                    mouseDownLeft = false;
                    mouseDownRight = false;
                    Cursor.Current = Cursors.Default;
                    // make graph
                    CreateGraph(true, 0.0f);
                    // redraw map
                    trb1_ValueChanged(null, null);
                }
            }
        }
        // Method to show point value(x,y,value) on mouse move
        private void axMap1_MouseMove(object sender, AxMapWinGIS._DMapEvents_MouseMoveEvent e)
        {
            double x1 = 0.0, y1 = 0.0;
            int nxb, nyb;
            //Convert to Grid coordinates.
            axMap1.PixelToProj(e.x, e.y, ref x1, ref y1);
            grid.ProjToCell(x1, y1, out nxb, out nyb);
            //image.ProjectionToImage(x1, y1, out nxb,out nyb);
            double v = Convert.ToDouble(grid.get_Value(nxb, nyb));
            //double v = Convert.ToDouble(image.get_Value(nxb, nyb));
            if (v > 99.9 || v < -99.9)
            {
                this.statusBar1.Panels[0].Text = "X = " + x1.ToString("0.0") + " Y = " + y1.ToString("0.0") + " Value = " + v.ToString("0.0");
            }
            else
            {
                this.statusBar1.Panels[0].Text = "X = " + x1.ToString("0.0") + " Y = " + y1.ToString("0.0") + " Value = " + v.ToString("0.0000");
            }
        }

        #endregion
  
        

        private void AddLayer(string mapFile, bool bContour, bool firstTime)
        {
            MapWinGIS.GridColorScheme gridScheme;
            image = new MapWinGIS.Image();
            MapWinGIS.Utils utils;
            MapWinGIS.GridColorBreak gcb;
            OpenFileDialog openDlg = new OpenFileDialog();

            int handle = 0;
            string ext;

            //initialize dialog
            openDlg.Filter = "Supported Formats|*.shp;*.bgd;*asc|Shapefile (*.shp)|*.shp|Binary Grids (*.bgd)|*.bgd|ASCII Grids (*.asc)|*.asc|TIFF (*.tif)|*.tif";
            openDlg.CheckFileExists = true;


            // check if MapFile exists if not Filedialog, get extension
            if (File.Exists(mapFile))
            {
                ext = System.IO.Path.GetExtension(mapFile);
            }
            else
            {
                if (openDlg.ShowDialog(this) == DialogResult.OK)
                {
                    ext = System.IO.Path.GetExtension(openDlg.FileName);
                    mapFile = openDlg.FileName;
                }
                else
                {
                    return;
                }
            }
            //MessageBox.Show(ext);

            if (ext == ".bgd" || ext == ".asc" || ext == ".tif")
            {
                //MessageBox.Show(mapFile);
                utils = new MapWinGIS.UtilsClass();
                gridScheme = new MapWinGIS.GridColorScheme();
                /*if (firstTime)
                {*/
                    grid = new MapWinGIS.GridClass();
                    //open the grid
                    if (ext == ".tif")
                    {
                        image.Open(mapFile, MapWinGIS.ImageType.TIFF_FILE, true, null);
                    }
                    else
                    {
                        grid.Open(mapFile, MapWinGIS.GridDataType.ByteDataType, true, MapWinGIS.GridFileType.UseExtension, this);
                    }
                /*}*/
                //create a coloring scheme for the image
 //               float[] rowVals = new float[2];
 //               float testRow = 0.0F;

 //               grid.GetFloatWindowGetFloatWindow(1, 1, 83, 84, ref rowVals[0]);
 //               MessageBox.Show(testRow.ToString() + " " + rowVals[1].ToString());
                ColorSchemes_velsto csv1 = new ColorSchemes_velsto();
                gridScheme = csv1.setColorScheme(cb1.SelectedIndex + 1, gridScheme, graphCreated,
                    leftReal, rightReal, 
                    Convert.ToDouble(grid.Minimum), Convert.ToDouble(grid.Maximum));
                double lightInt, lightAzi, lightElev;
                lightInt = (double)trb1.Value / ((double)(trb1.Maximum - trb1.Minimum));
                lightAzi = (double)trb2.Value;
                lightElev = (double)trb3.Value;
                gridScheme.LightSourceIntensity = lightInt;
                gridScheme.SetLightSource(lightAzi, lightElev);

                //gcb = new MapWinGIS.GridColorBreak();
                //Set the gradient model to use with the color break
                //gcb.GradientModel = MapWinGIS.GradientModel.Linear;
                //gridScheme.InsertBreak(gcb);


                //convert the grid to a image
                if (ext != ".tif")
                {
                    image = utils.GridToImage(grid, gridScheme, this);
                }
                image.TransparencyColor = gridScheme.NoDataColor;
                image.UseTransparencyColor = true;
                
                //Display the gradient model used by the color break
                //MsgBox(break.GradientModel.ToString)

                //image.UpsamplingMode = MapWinGIS.tkInterpolationMode.imNone;
                //image.DownsamplingMode = MapWinGIS.tkInterpolationMode.imNone;
                //add the image to the legend and map
                handle = legend1.Layers.Add(image, true);

                if (legend1.Layers.IsValidHandle(handle))
                {
                    //set the layer name
                    //legend1.Map.set_LayerName(handle, System.IO.Path.GetFileNameWithoutExtension(grid.Filename));
                    legend1.Map.set_LayerName(handle, "Grid");

                    //set's the legend layer type, this displays a default icon in the legend (line shapefile, point shapefile,polygon shapefile,grid,image)
                    if (ext == ".tif")
                    {
                        legend1.Layers.ItemByHandle(handle).Type = MapWindow.Interfaces.eLayerType.Image;
                        axMap1.AddLabel(handle,"Dit is een Image",0, 0.0, 0.0,MapWinGIS.tkHJustification.hjCenter);
                    }
                    else
                    {
                        legend1.Layers.ItemByHandle(handle).Type = MapWindow.Interfaces.eLayerType.Grid;
                    
                    }
                        
                    //set coloring scheme
                    //when applying a coloring scheme to a shapfile use axMap1.ApplyLegendColors(ShapefileColorScheme)
                    //when applying a coloring scheme for a grid or image use axMap1.SetImageLayerColorScheme(handle,GridColorScheme
                    axMap1.SetImageLayerColorScheme(legend1.SelectedLayer, gridScheme);
                    legend1.Layers.ItemByHandle(legend1.SelectedLayer).Refresh();
                    handle_grid = handle;
                }
                //close the grid Commented out due to use reuse of grid 
                //in Contouring and Repaint
                //grid.Close();
            }
            else if (ext == ".shp")
            {
                shpfile_cont = new MapWinGIS.ShapefileClass();
                
                //open the shapefile
                shpfile_cont.Open(mapFile, this);
                grid.AssignNewProjection(shpfile_cont.Projection);
     
                // generate labels
                if (bContour)
                {
                    shpfile_cont = new MapWinGIS.ShapefileClass();

                    //open the shapefile
                    shpfile_cont.Open(mapFile, this);
                    grid.AssignNewProjection(shpfile_cont.Projection);
                    shpfile_cont.Labels.Generate("[Grid_value]", MapWinGIS.tkLabelPositioning.lpLongestSegement, true);
                    //add the shapefile to the map and legend
                    handle = legend1.Layers.Add(shpfile_cont, true);
                }
                else
                {
                    shpfile_depth = new MapWinGIS.ShapefileClass();

                    //open the shapefile
                    shpfile_depth.Open(mapFile, this);
                    grid.AssignNewProjection(shpfile_depth.Projection);
                    double x = 0.0, y = 0.0, z = 0.0;
                    string w;
                    //double meanz = 0.0, stdevz = 0.0;
                    double sumz = 0.0, sumsqr = 0.0;
                    int numpoints = 0;
                    for (int i = 0; i < shpfile_depth.NumShapes; i++)
                    {
                        // create labels
                        shpfile_depth.get_Shape(i).get_XY(0, ref x, ref y);
                        z = (double)shpfile_depth.get_CellValue(1, i);
                        if (z < Constants.SHP_NODATA)
                        {
                            sumz = sumz + z;
                            numpoints++;
                        }
                        w = (string)shpfile_depth.get_CellValue(2, i);
                        shpfile_depth.Labels.AvoidCollisions = false;
                        shpfile_depth.Labels.FontSize = 4;
                        string labexp;
                        if (se.MapType == Constants.MAP_ZDEV_WELL2)
                        {
                            labexp = "[well]";
                        }
                        else
                        {
                            labexp = "[well]+" + "\"\n\"" + "+[depth]";
                        }
                        shpfile_depth.Labels.Generate(labexp, MapWinGIS.tkLabelPositioning.lpLongestSegement, true);
                        /*
                        shpfile_depth.Labels.FontSize = 4;
                        shpfile_depth.Labels.AvoidCollisions = false;
                        shpfile_depth.Labels.ScaleLabels = true;
                        shpfile_depth.Labels.MinDrawingSize = 4;//?
                        shpfile_depth.Labels.AddLabel(z.ToString("0.0"), x - (se.MapNcols/20)*se.MapCellsize, y - (se.MapNrows/30)*se.MapCellsize, 0.0,0);
                        shpfile_depth.Labels.AddLabel(w, x - (se.MapNcols/20)*se.MapCellsize, y + (se.MapNrows/30)*se.MapCellsize, 0.0,0);
                        */
                    }
                    // calc and plot mean and standard deviation
                    meanz = sumz / numpoints;
                    se.Res_mean = meanz;
                    for (int i = 0; i < shpfile_depth.NumShapes; i++)
                    {
                        z = (double)shpfile_depth.get_CellValue(1, i);
                        if (z < Constants.SHP_NODATA)
                        {
                            sumsqr = sumsqr + ((z - meanz) * (z - meanz));
                        }
                    }
                    stdevz = Math.Sqrt(sumsqr / numpoints);
                    se.Res_stdev = stdevz;
                    if ((resWorkflow && rwf_phase == Constants.RWF_PHASE_RESID) ||
                        (!resWorkflow && se.MapType == Constants.MAP_RES_KRIG))
                    {
                        lbres_mean.Text = "Residuals Mean : " + meanz.ToString("0.0");
                        lbres_stdev.Text = "Residuals Stdev : " + stdevz.ToString("0.0");
                        lbres_mean.Visible = true;
                        lbres_stdev.Visible = true;
                    }
                    else
                    {
                        lbres_mean.Visible = false;
                        lbres_stdev.Visible = false;
                    }
                    //add the shapefile to the map and legend
                    handle = legend1.Layers.Add(shpfile_depth, true);
                }
                
                //set the layer name
                if (bContour)
                {
                    handle_contour = handle;
                    legend1.Map.set_LayerName(handle, "Contour");
                }
                else
                {
                    handle_depth = handle;
                    legend1.Map.set_LayerName(handle, "Well Depth");
                    //legend1.Map.set_LayerName(handle, System.IO.Path.GetFileNameWithoutExtension(shpfile.Filename));
                    //shpfile_open = shpfile.Clone();
                } 
                if (!bContour) { shpfile_opened = true; }
            }
            //initiate MouseMoveEvent and clear the statusbar
            axMap1.SendMouseMove = true;
            legend1.Layers.ExpandAll();
            statusBar1.Panels[0].Text = "";
            progressBar1.Value = 0;
        } 


		#region ICallback Members

		public void Error(string KeyOfSender, string ErrorMsg)
		{
			// TODO:  Add Form1.Error implementation
		}

		public void Progress(string KeyOfSender, int Percent, string Message)
		{
			progressBar1.Value = Percent;
			statusBar1.Panels[0].Text =Message;
		}

		#endregion


        private void getHist(out ArrayList arX, out ArrayList arY, out float minD, out float maxD, out float maxS)
        {
            int nrHist = 200;
            double histInterval = 0.0, histMin = 0.0, histMax = 0.0;
            List<double> lsHistValues;
            arX = new ArrayList();
            arY = new ArrayList();
            List<HistInterval> lsHist = new List<HistInterval>();
            HistInterval hint;
            XYPointFile xyz1 = new XYPointFile();
            lsHistValues = xyz1.getContourIntervals(nrHist, Convert.ToDouble(grid.Minimum),
                                                        Convert.ToDouble(grid.Maximum));
            histInterval = lsHistValues[1] - lsHistValues[0];
            histMin = lsHistValues[0] - histInterval;
            histMax = lsHistValues[lsHistValues.Count - 1] + histInterval;
            //MessageBox.Show(lsHistValues.Count.ToString() + " " + histInterval.ToString() + " " + histMin.ToString() + " " + histMax.ToString());
            // Add first interval
            hint = new HistInterval(histMin, lsHistValues[0], 0); 
            lsHist.Add(hint);
            // Add Intermediate intervals
            for (int i=0; i<lsHistValues.Count-1 ; i++)
            {
                hint = new HistInterval(lsHistValues[i], lsHistValues[i+1], 0);
                lsHist.Add(hint);
            }
            // Add last interval
            hint = new HistInterval(lsHistValues[lsHistValues.Count - 1], histMax, 0);
            lsHist.Add(hint);
            //MessageBox.Show(lsHist.Count.ToString());
            cBack cb = new cBack();
            int p1 = 0;
            int numOfCol = grid.Header.NumberCols;
            int numOfRow = grid.Header.NumberRows;
            double val = 0.0;
            double dval = 0.0;
            double dnodata = (double)grid.Header.NodataValue;
            int k = 0;
            cb.Show();
            for (int jc = 0; jc < numOfCol; jc++)
            {
                p1++;
                if (p1 == 10)
                {
                    cb.Progress("", (int)(100.0 * ((double)jc / (double)numOfCol)), "Creating Histogram");
                    p1 = 0;
                }
                for (int jr = 0; jr < numOfRow; jr++)
                {

                    val = Convert.ToDouble(grid.get_Value(jc, jr));
                    try
                    {
                        if (val != dnodata)
                        {
                            dval = ((val - histMin) / histInterval);
                            k = (int)dval;
                            if (k >= (lsHist.Count - 1)) { k = lsHist.Count - 1; }
                            lsHist[k].Y++;
                        }
                        else
                        {
                            //MessageBox.Show(k.ToString());
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }

                }
            }
            cb.Close();
            minD = 999999.9f;
            maxD = -9999999.9f;
            maxS = -9999999.9f;
            for (int i=0; i<lsHist.Count; i++)
            {
                arX.Add(lsHist[i].X_from);
                arY.Add(lsHist[i].Y);
                if (lsHist[i].X_from<minD)
                {
                    minD = (float) lsHist[i].X_from;
                }
                if (lsHist[i].X_till>maxD)
                {
                    maxD = (float) lsHist[i].X_till;
                }
                if (lsHist[i].Y>maxS)
                {
                    maxS = (float) lsHist[i].Y;
                }
            }
            return;
        }

        private void CreateGraph(bool mmredraw, float x)
        {
            ////Create an instance of graphicHistogram.cs file.
            graphicHistogram = new GraphicHistogram();
            ////Set the height for the graph image.
            graphicHistogram.Height = 90;
            ////Set the width for the graph image.
            graphicHistogram.Width = 500;
            ////Set the Slices(partition in Axis) for X and Y Axis.
            graphicHistogram.XSlice = 20;
            graphicHistogram.YSlice = 20;
            ////Set the Title for both Axis.
            graphicHistogram.XAxisText = "Value";
            graphicHistogram.YAxisText = "Hist";
            
            //graphicHistogram.XrealValue = 10.0F;
            //graphicHistogram.YrealValue = 10.0F;
            
            ////Set the Graph Title.;
            graphicHistogram.Title = "Histogram";
            ////Set the Backcolor and forecolor for the graph title.
            graphicHistogram.TitleBackColor = Color.White;
            graphicHistogram.TitleForeColor = Color.Black;
            ////Initialize the graph object to draw.
            graphicHistogram.InitializeGraph();
            // calc histogram array when graph first drafted
            if (!graphCreated)
            {
                arx1 = new ArrayList();
                ary1 = new ArrayList();
                minD = 0.0f;
                maxD = 0.0f;
                maxS = 0.0f;
                this.getHist(out arx1, out ary1, out minD, out maxD, out maxS);
            }
            graphicHistogram.MinD = minD;
            graphicHistogram.XrealValue = (float)((maxD - minD) * 50) / (graphicHistogram.Width - 
                (2 * graphicHistogram.XSlice));
            graphicHistogram.GraphXprop = 50 / graphicHistogram.XrealValue;
            graphicHistogram.YrealValue = (float)(maxS * 50) / (graphicHistogram.Height - 
                (2 * graphicHistogram.YSlice));
            graphicHistogram.X1Axis = arx1;
            graphicHistogram.Y1Axis = ary1;
            xLeft = 80.0f;
            xRight = 300.0f;//350
            graphicHistogram.DrawLine(xLeft, -10, xLeft , 110);
            graphicHistogram.DrawLine(xRight, -10, xRight, 110);
            // (re)calc leftReal,rightReal required for colors in histogram and redrawing map
            leftReal = (xLeft / graphicHistogram.GraphXprop) + minD;
            rightReal = (xRight / graphicHistogram.GraphXprop) + minD;
            // get colors for histogram
            ColorSchemes_velsto csc1 = new ColorSchemes_velsto();
            graphicHistogram.XYColor = csc1.setHistColorScheme(cb1.SelectedIndex + 1, arx1, 
                                                               leftReal, rightReal,
                                                               Convert.ToDouble(grid.Minimum), Convert.ToDouble(grid.Maximum));
            //MessageBox.Show(graphicHistogram.XYColor.Count.ToString() + " " + graphicHistogram.X1Axis.Count.ToString());
            // draw histogram
            graphicHistogram.CreateLines();
            // draw line when dragged
            if (mmredraw && (mouseDownLeft || mouseDownRight))
            {
                graphicHistogram.DrawLine(x - graphicHistogram.XSlice, -10, x - graphicHistogram.XSlice, 110);
            }
            // Draw XAxis values
            List<double> lsXAxisValues;
            int nrXAxis = 6;
            XYPointFile xyz1 = new XYPointFile();
            lsXAxisValues = xyz1.getContourIntervals(nrXAxis, (double) minD,(double) maxD);
            graphicHistogram.SetXAxis2(lsXAxisValues);
            // Draw Yaxis values
            Bitmap bmp = graphicHistogram.GetGraph();
            this.pb1.Image = bmp;
            graphCreated = true;
            // redraw map when graph first created or mouse up when lines dragged
            if (!mmredraw)
            {
                trb1_ValueChanged(null, null);
            }
            return;
        }
    }
}
